import Observer from "./Observer.js"

export default class Vue{

    constructor(obj){
        
        // 1、数据挂载：
        for(let key in obj.data){
            // 1、订阅，遍历dom，完成订阅
            let obserser = new Observer();

            let rootDom = document.querySelector(obj.el);

            for(let i=0;i<rootDom.children.length;i++){
                if(rootDom.children[i].innerHTML.includes("{{"+key+"}}")){       

                    let oldHTML = rootDom.children[i].innerHTML;

                    obserser.addSubscriber(function(newVal){                      
                        rootDom.children[i].innerHTML = oldHTML.replace(new RegExp("{{"+key+"}}","g"),newVal);
                    })

                }
            }

            // 2、给每个属性加setter和getter 
            // this[key] = obj.data[key];
            let value = obj.data[key];//value是用来存储数据的

            Object.defineProperty(this,key,{
                set:function(newVal){
                    if(value===newVal){
                        return;
                    }
                    value = newVal;
                    console.log(key+"被改了",newVal);
                    obserser.publish(newVal);
                },
                get:function(){
                    return value;
                }
            })

        }

       

        // 2、模板（初次）渲染（把数据显示在html上）；
        let rootDom = document.querySelector(obj.el);
        let htmlStr = rootDom.innerHTML;

        for(let key in obj.data){
            htmlStr = htmlStr.replace(new RegExp("{{"+key+"}}","g"),obj.data[key]);
        }

        rootDom.innerHTML = htmlStr;

    }

}